<template>
    <el-container id="logs-container">
        <el-form :inline="true" :model="formInline">
            <!-- 团队选择框（根据showTeamSelect决定是否显示） -->
            <el-form-item v-if="showTeamSelect" label="团队">
                <el-select-v2 allow-create v-model="internalTeamId" placeholder="请选择团队" clearable @change="teamchange"
                    :options="teamsOptions" filterable />
            </el-form-item>

            <!-- 学员选择框 -->
            <el-form-item label="学员">
                <el-select-v2 v-model="usersId" placeholder="请选择学员" multiple :options="userOptions" clearable
                    collapse-tags collapse-tags-tooltip filterable :style="{ width: '300px' }" allow-create />
            </el-form-item>

            <el-form-item label="时间">
                <el-date-picker v-model="time" :style="{ width: '300px' }" type="daterange" range-separator="-"
                    start-placeholder="开始日期" end-placeholder="结束日期" :shortcuts="shortcuts" />
            </el-form-item>

            <el-form-item label="类型">
                <el-select v-model="type" :style="{ width: '120px' }">
                    <el-option v-for="(cfg, value) in filteredLogTypes" :key="value" :label="cfg.label"
                        :value="value" />
                </el-select>
            </el-form-item>

            <el-row>
                <el-col :span="12">
                    <el-form-item label="总条数:">{{ count }} &nbsp;&nbsp;&nbsp;</el-form-item>
                    <el-form-item label="用户数:">{{ usercount }}</el-form-item>
                </el-col>
                <el-col :span="12" class="text-right">
                    <el-button-group>
                        <el-button type="primary" @click="start">查询</el-button>
                        <el-button type="primary" @click="() => download()">下载当前页</el-button>
                        <el-button type="primary" @click="() => download(true)">下载全部</el-button>
                    </el-button-group>
                </el-col>
            </el-row>
        </el-form>

        <el-table v-loading="loading" :data="mytableDate" :height="height">
            <el-table-column v-if="showTeamSelect" prop="_teamids_" label="团队ID" width="100" show-overflow-tooltip />
            <el-table-column prop="_userid_" label="用户ID" width="100" />
            <el-table-column prop="_username_" label="用户名" width="150" show-overflow-tooltip />
            <el-table-column prop="_method_" label="日志类型" width="100">
                <template #default="{ row }">
                    {{ getLogTypeName(row._method_) }}
                </template>
            </el-table-column>
            <el-table-column prop="questionname" label="题目信息" max-width="200" show-overflow-tooltip>
                <template #default="{ row }">
                    <div v-if="row.questionid">
                        {{ row.questionname }} ( ID: {{ row.questionid }} )
                    </div>
                </template>
            </el-table-column>
            <el-table-column prop="action" label="操作类型" width="150">
                <template #default="{ row }">
                    {{ getActionName(row['body.action']) }}
                </template>
            </el-table-column>
            <el-table-column prop="_method_" label="详细信息" width="" show-overflow-tooltip>
                <template #default="{ row }">
                    <template v-if="row._method_ === AILogMethod.AiSolution">
                        <div class="detail-group">
                            <div class="detail-item">
                                <span class="detail-label">方案:</span>
                                <span class="detail-value">
                                    {{ row['body.solution_index'] }}
                                    ( ID: {{ row['body.solution_id'] }})
                                </span>
                            </div>
                            <div class="detail-item">
                                <span class="detail-label">步骤:</span>
                                <span type="primary" class="detail-value">{{ row['body.step_index'] }} / {{
                                    row['body.total_steps']
                                    }}</span>
                            </div>
                        </div>
                    </template>
                    <template v-else-if="row._method_ === AILogMethod.CodeAssistance">
                        <div class="detail-group">
                            <div class="detail-item">
                                <span class="detail-label">代码长度:</span>
                                <span class="detail-value">
                                    {{ row['body.code_length'] }}
                                    ( {{ row['body.language'] }} )
                                </span>
                            </div>
                            <div class="detail-item margin-left20" v-if="row['body.code']">
                                <el-button type="primary" @click="showCodeDialog(row)" class="view-code-btn">
                                    查看代码
                                </el-button>
                            </div>
                        </div>
                    </template>
                </template>
            </el-table-column>
            <el-table-column prop="time" label="时间" width="180" />
        </el-table>

        <el-footer>
            <el-pagination class="pager" :page-sizes="[10, 20, 50, 100]" :page-size="formInline.line"
                :current-page="currentPage" layout="total, sizes, prev, pager, next, jumper" :total="count"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </el-footer>

        <el-dialog v-model="codeDialogVisible" title="代码详情" draggable width="70%">
            <template #header>
                <span class="icon-text el-dialog__header-title">
                    <el-icon class="text-primary">
                        <Guide />
                    </el-icon>
                    使用AI代码协助时的代码
                </span>
            </template>
            <div class="code-detail">
                <div class="solution-header">
                    <h3>{{ currentRow.questionid }}-{{ currentRow.questionname || '未知题目' }}</h3>
                    <div class="meta-tags">
                        <el-tag size="small">{{ currentRow['body.language'] }}</el-tag>&nbsp;
                        <el-button size="small" type="primary" plain @click="copyToClipboard()" :icon="DocumentCopy">
                            复制代码
                        </el-button>
                    </div>
                </div>

                <pre v-highlight><code :class="'language-' + currentRow['body.language']">{{ currentRow['body.code'] }}</code>
        </pre>
            </div>
        </el-dialog>
    </el-container>
</template>

<script setup lang="ts">
import { DocumentCopy, Guide } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import moment from 'moment';
import { computed, inject, onMounted, reactive, ref, watch } from 'vue';
import { asyncselectteamselectuser } from '../../api/index';
import FetchApi from '../../logs/api';
import Studycodemodel from '../../mysql_interface/studycodemodel';
import { AILogAction, AILogActionCfg, AILogMethod, AILogTypeCfg } from '../../util/data';
import { getExceltodownload } from '../../util/excel';
const tenant_id = inject<string | undefined>("tenant_id", undefined);
const props = defineProps({
    teamid: { type: Number, default: undefined },
    logTypes: {
        type: Array as () => AILogMethod[],
        default: () => [AILogMethod.All, AILogMethod.AiSolution, AILogMethod.CodeAssistance]
    },
    defaultDays: { type: Number, default: 7 },
    // 新增props
    teams: {  // 从外部传入团队列表
        type: Array as () => { ID: number, name: string }[],
        default: () => []
    },
    currentUser: {  // 从外部传入当前用户信息
        type: Object as () => Studycodemodel.Iuser | undefined,
        required: true
    },
    tenantId: {
        type: String,
        default: undefined
    },
    height: { type: String, default: '75vh' }
});

const shortcuts = [
    { text: '最近7天', value: () => [new Date(Date.now() - 3600 * 1000 * 24 * 7), new Date()] },
    { text: '本周', value: () => [moment().day(1).toDate(), new Date()] },
    { text: '本月', value: () => [moment().date(1).toDate(), new Date()] },
    { text: '最近30天', value: () => [moment().subtract(30, 'days').toDate(), new Date()] }
];

const formInline = reactive({
    query: '*',
    line: 20,
    offset: 0,
    projectName: 'htetest1',
    logstoreName: 'ojhte',
    from: new Date(moment().subtract(props.defaultDays, 'days').unix() * 1000),
    to: new Date(moment().add(1, 'days').unix() * 1000),
    reverse: true
});

const loading = ref(false);
const tableData = ref<any[]>([]);
const currentPage = ref(1);
const count = ref(0);
const usercount = ref(0);
const usersId = ref<number[]>([]);
const type = ref<AILogMethod>(AILogMethod.All);
const internalTeamId = ref<number>();
const teamUser = ref<Studycodemodel.Iteamuser[]>([]);

const teams = ref(props.teams);
const user = ref(props.currentUser);

// 计算属性
const showTeamSelect = computed(() => props.teamid === undefined);
const teamid = computed(() => props.teamid ?? internalTeamId.value);
const teamsOptions = computed(() => teams.value.map(e => ({ value: e.ID, label: e.name })));
const userOptions = computed(() => teamUser.value.map(e => ({
    value: e.userid,
    label: e.user?.xingming ? `${e.user.xingming} (${e.user?.name})` : e.user?.name
})));
const filteredLogTypes = computed(() => {
    return Object.fromEntries(
        Object.entries(AILogTypeCfg).filter(([key]) =>
            props.logTypes.includes(key as AILogMethod)
        )
    );
});

const time = computed({
    get() {
        return [formInline.from, formInline.to];
    },
    set(v: [Date, Date]) {
        // 如果清空时间范围，则设置为最近一年
        [formInline.from, formInline.to] = v || [new Date(moment().subtract(1, 'year').startOf('day').toDate()), new Date(moment().endOf('day').toDate())];
    }
});
const mytableDate = computed(() => tableData.value.map(log => ({
    ...log,
    // body: JSON.parse(log.body),
    time: moment(Number(log.__time__) * 1000).format('YYYY-MM-DD HH:mm:ss')
})));

function getLogTypeName(_method_: AILogMethod) {
    return _method_ ? AILogTypeCfg[_method_]?.label || _method_ : '-';
}
function getActionName(action?: AILogAction) {
    return action ? AILogActionCfg[action]?.label || action : '-';
}

async function start() {
    if (!user.value?.ID) {
        ElMessage.info("请先登录");
        return;
    }
    if (!user.value.isAdmin) {
        ElMessage.error("权限不足");
        return;
    }
    let query = '*';
    let where = 'where 1 = 1';
    if (type.value === AILogMethod.All) {
        query += ` and (_method_:${AILogMethod.AiSolution} or _method_:${AILogMethod.CodeAssistance})`;
    } else {
        query += ` and _method_:${type.value}`;
    }
    if (teamid.value) query += ` and _teamids_:${teamid.value}`;
    if (usersId.value.length) where += ` and _userid_ in (${usersId.value.join(',')})`;
    const fromSec = Math.floor(formInline.from.getTime() / 1000);
    const toSec = Math.floor(formInline.to.getTime() / 1000);
    where += ` and __time__ >= ${fromSec} and __time__ <= ${toSec}`;
    formInline.query = query;
    try {
        loading.value = true;
        const [dataRes, countRes] = await Promise.all([
            FetchApi({
                ...formInline,
                query: `${query} | select * ${where} order by __time__ desc limit ${formInline.offset},${formInline.line}`
            }),
            FetchApi({
                ...formInline,
                offset: 0,
                query: `${query} | SELECT count(*) as count, count(DISTINCT(_userid_)) as usercount ${where}`
            })
        ]);
        loading.value = false;
        tableData.value = dataRes.data;
        count.value = Number(countRes.data[0]?.count || 0);
        usercount.value = Number(countRes.data[0]?.usercount || 0);
    } catch (error) {
        ElMessage.error('获取日志失败: ' + (error as Error).message);
    }
}
async function getcount(query: string, where: string) {
    const { data } = await FetchApi({
        ...formInline,
        offset: 0,
        query: `${query} | SELECT count(*) as count, count(DISTINCT(_userid_)) as usercount ${where}`
    });
    count.value = Number(data[0]?.count || 0);
    usercount.value = Number(data[0]?.usercount || 0);
}

function handleSizeChange(size: number) {
    formInline.line = size;
    start();
}
function handleCurrentChange(page: number) {
    formInline.offset = formInline.line * (page - 1);
    currentPage.value = page;
    start();
}

async function teamchange(teamId: number) {
    internalTeamId.value = teamId;
    await loadTeamUsers(teamId);
    start();
}
async function loadTeamUsers(teamId: number) {
    try {
        teamUser.value = await asyncselectteamselectuser({ teamid: teamId });
    } catch {
        ElMessage.error('获取团队成员失败');
    }
}

async function download(all = false) {
    try {
        const headers = ['用户ID', '用户名', '日志类型', '题目信息', '操作类型', '详细信息', '时间'];
        let data = mytableDate.value.map(log => [
            log._userid_,
            log._username_,
            getLogTypeName(log._method_),
            log.questionid ? `${log.questionname} (ID:${log.questionid})` : '',
            getActionName(log['body.action']),
            log._method_ === AILogMethod.AiSolution
                ? `方案${log['body.solution_index']} (${log['body.solution_id']}), 步骤${log['body.step_index']}/${log['body.total_steps']}`
                : `代码长度: ${log['body.code_length']} (${log['body.language']}), 代码: ${log['body.code']}`,
            log.time
        ]);
        if (all) {
            const batchSize = 99;
            const totalRequests = Math.ceil(count.value / batchSize);
            // 使用Promise.all并行请求所有数据
            const requests = Array.from({ length: totalRequests }, (_, i) => {
                const start = i * batchSize;
                return FetchApi({
                    ...formInline,
                    query: formInline.query + ` | select * order by __time__ desc limit ${start},${batchSize}`
                });
            });

            const results = await Promise.all(requests);
            data = results.flatMap(res =>
                res.data.map(log => [
                    log._userid_,
                    log._username_,
                    getLogTypeName(log._method_),
                    log.questionid ? `${log.questionname} (ID:${log.questionid})` : '',
                    getActionName(log['body.action']),
                    log._method_ === AILogMethod.AiSolution
                        ? `方案${log['body.solution_index']} (${log['body.solution_id']}), 步骤${log['body.step_index']}/${log['body.total_steps']}`
                        : `代码长度: ${log['body.code_length']} (${log['body.language']}), 代码: ${log['body.code']}`,
                    moment(Number(log.__time__) * 1000).format('YYYY-MM-DD HH:mm:ss')
                ])
            );
        }
        const team = teams.value.find(t => t.ID === teamid.value);
        const fileName = `${team?.name || 'AI日志'}_${moment(formInline.from).format('YYYYMMDD')}-${moment(formInline.to).format('YYYYMMDD')}`;
        getExceltodownload([headers, ...data], fileName);
    } catch (error) {
        ElMessage.error('导出失败: ' + (error as Error).message);
    }
}

// 初始化
onMounted(async () => {
    try {
        // await store.dispatch('actionteam', { tenant_id });
        if (props.teamid !== undefined) {
            await loadTeamUsers(props.teamid);
        }
        await start();
    } catch (e) {
        ElMessage.error('初始化失败: ' + (e as Error).message);
    }
});

// 监听props.teamid变化
watch(() => props.teamid, async (newVal) => {
    if (newVal !== undefined) {
        await loadTeamUsers(newVal);
        // start();
    }
});

// 添加代码查看对话框
const codeDialogVisible = ref(false);
const currentRow = ref();

const showCodeDialog = (row: any) => {
    currentRow.value = row;
    codeDialogVisible.value = true;
};
const copyToClipboard = async () => {
    try {
        await navigator.clipboard.writeText(currentRow.value['body.code']);
        ElMessage.success('代码已复制到剪贴板');
    } catch (err) {
        ElMessage.error('复制失败: ' + (err as Error).message);
    }
};

</script>

<style>
.detail-group {
    display: flex;
    align-items: center;
    justify-content: center;
}

.detail-item {
    margin-bottom: 6px;
    display: flex;
    align-items: center;
}

.detail-label {
    font-weight: bolder;
    margin: 0 10px;
    color: #606266;
}

.detail-value {
    color: #303133;
}

.view-code-btn {
    /* margin-top: 8px; */
}

/* 代码预览样式 */
pre {
    background-color: #f6f8fa;
    padding: 16px;
    border-radius: 4px;
    overflow: auto;
    max-height: 60vh;
    font-family: 'Courier New', Courier, monospace;
    white-space: pre-wrap;
    word-wrap: break-word;
}

/* 对话框样式 */
.solution-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 12px;
    border-bottom: 1px solid #ebeef5;
}

.solution-header h3 {
    margin: 0;
    font-size: 18px;
    color: #303133;
}

.meta-tags {
    display: flex;
    gap: 8px;
    align-items: center;
}

.code-detail pre {
    margin: 0;
    background: #f6f8fa;
    padding: 16px;
    border-radius: 4px;
    overflow: auto;
    max-height: 60vh;
}
</style>